package cc.rengu.igas.bomp.core.service.trans;

import cc.rengu.igas.bomp.common.constant.BompAppParamConstant;
import cc.rengu.igas.bomp.common.dao.AgentInfoMapper;
import cc.rengu.igas.bomp.common.dao.OrganizationMapper;
import cc.rengu.igas.bomp.common.dao.impl.AgentInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.OrganizationMapperImpl;
import cc.rengu.igas.bomp.common.entity.AgentInfo;
import cc.rengu.igas.bomp.common.entity.ManagerInfo;
import cc.rengu.igas.bomp.common.entity.Organization;
import cc.rengu.igas.bomp.common.enums.RespCodeEnum;
import cc.rengu.igas.bomp.core.service.base.ManageService;
import cc.rengu.igas.bomp.facade.bean.AgentMchntInfoBean;
import cc.rengu.igas.bomp.facade.request.AgentMchntListQueryRequest;
import cc.rengu.igas.bomp.facade.response.AgentMchntListQueryResponse;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.bean.PageInfo;
import cc.rengu.oltp.utility.bean.PageResult;
import cc.rengu.oltp.utility.util.BeanUtil;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 代理机构列表查询
 * Created by 赵奎伍
 * <p/>
 * 无条件查询时显示全法人行课件代理机构及用户签约机构及其下属机构管理的代理机构
 */
public class AgentMchntListQueryService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        AgentMchntListQueryRequest mchntImageInfoQueryRequest = new AgentMchntListQueryRequest();
        ConvertUtil.convertOutput(mchntImageInfoQueryRequest);
        return mchntImageInfoQueryRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        AgentMchntListQueryRequest agentMchntListQueryRequest = (AgentMchntListQueryRequest) request;
        AgentMchntListQueryResponse agentMchntListQueryResponse = new AgentMchntListQueryResponse();
        BeanUtil.beanCopy(agentMchntListQueryRequest, agentMchntListQueryResponse);
        /* 按照接口转换基础产品信息并响应给请求方 */
        BizResponse bizResponse = new BizResponse();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setResult(agentMchntListQueryResponse);

        String instId = agentMchntListQueryRequest.getHeader().getInstId();
        String channelId = agentMchntListQueryRequest.getHeader().getChanlId();

        //region 查询字段
        String agentMchntNo = agentMchntListQueryRequest.getAgentMchntNo();
        String agentMchntName = agentMchntListQueryRequest.getAgentMchntName();
        String signInstId = agentMchntListQueryRequest.getSignInstId();
        int pageIndex = agentMchntListQueryRequest.getPageIndex();
        int pageSize = agentMchntListQueryRequest.getPageSize();
        rglog.debug("查询字段:agentMchntNo<{}>,agentMchntName<{}>,signInstId<{}>,pageIndex<{}>,pageSize<{}>", agentMchntNo, agentMchntName, signInstId, pageIndex, pageSize);
        //endregion

        AgentInfoMapper agentInfoMapper = new AgentInfoMapperImpl();
        if (BompAppParamConstant.MCMP_CHANNEL.equals(channelId)) {
            if (-1 == pageIndex || -1 == pageSize) {
                //不分页
                /* 根据代理机构编号查询或代理机构名称模糊查询或根据签约机构代码查询 */
                List<AgentInfo> agentInfoList = agentInfoMapper.selectAgentInfoByAgentMchntNoOrAgentMchntNameOrSignInstId(instId, agentMchntNo, agentMchntName, signInstId);
                if (CollectionUtils.isEmpty(agentInfoList)) {
                    agentMchntListQueryResponse.setTotalPage(BompAppParamConstant.INT_ZERO);
                    agentMchntListQueryResponse.setTotalRows(BompAppParamConstant.INT_ZERO);
                    return bizResponse;
                } else {
                    /* 按照创建时间降序排序 */
//                    agentInfoList = agentInfoList.stream().sorted(Comparator.comparing(AgentInfo::getCreateTime)).collect(Collectors.toList());
//                    Collections.reverse(agentInfoList);
                    int totalRows = agentInfoList.size();//过滤前总记录数
                    List<AgentMchntInfoBean> agentMchntInfoBeanList = new ArrayList<>();
                    agentInfoList.forEach(item -> convAgentInfo(item, agentMchntInfoBeanList));
                    /* 查询结果赋值 */
                    agentMchntListQueryResponse.setTotalRows(totalRows);//总记录数
                    agentMchntListQueryResponse.setAgentMchntInfoList(agentMchntInfoBeanList);
                }
            } else {
                //分页
                PageInfo pageInfo = new PageInfo();
                pageInfo.setPageIndex(pageIndex);
                pageInfo.setPageSize(pageSize);
                PageResult pageResult = agentInfoMapper.selectAgentInfoByAgentMchntNoOrAgentMchntNameOrSignInstIdPageInfo(instId, agentMchntNo, agentMchntName, signInstId, pageInfo);

                if (null == pageResult || null == pageResult.getPageInfo() || pageResult.getResult().isEmpty()) {
                    rglog.error("根据查询条件查询代理机构信息 pageResult 为null !");
                    rglog.info("根据查询条件查询到0条代理机构信息!");
                    agentMchntListQueryResponse.setTotalPage(BompAppParamConstant.INT_ZERO);
                    agentMchntListQueryResponse.setTotalRows(BompAppParamConstant.INT_ZERO);
                    agentMchntListQueryResponse.setRespCode(RespCodeEnum.QUERY_DATA_IS_NULL.getRespCode());
                    agentMchntListQueryResponse.setRespDesc(RespCodeEnum.QUERY_DATA_IS_NULL.getRespDesc());
                    return bizResponse;
                }

                /* 根据取出记录条数做对应处理 */
                List<AgentInfo> agentInfoList = new ArrayList<>();
                for (Object object : pageResult.getResult()) {
                    agentInfoList.add((AgentInfo) object);
                }

                rglog.info("SIZE=<{}>", pageResult.getResult().size());
                /* 按照创建时间降序排序 */
                agentInfoList = agentInfoList.stream().sorted(Comparator.comparing(AgentInfo::getCreateTime)).collect(Collectors.toList());
                Collections.reverse(agentInfoList);

                List<AgentMchntInfoBean> agentMchntInfoBeanList = new ArrayList<>();
                agentInfoList.forEach(item -> convAgentInfo(item, agentMchntInfoBeanList));

                agentMchntListQueryResponse.setAgentMchntInfoList(agentMchntInfoBeanList);
                agentMchntListQueryResponse.setTotalPage(pageResult.getPageInfo().getTotalPage());
                agentMchntListQueryResponse.setTotalRows(pageResult.getPageInfo().getTotalRows());
            }
        } else {
            //"WECHAT".equals(channelId) || "MOBILE".equals(channelId) || "PCWEB".equals(channelId)
            /* 根据多法人标识查询所有代理商信息*/
            String manageInstIds = null;
            //拓展经理信息已在【ManageService】中获取,签约机构及其下属机构,然后根据机构列表查询
            ManagerInfo managerInfo = (ManagerInfo) xmlTreeUtil.getXmlTreeObjectValue("managerInfo", ManagerInfo.class);
            if (managerInfo != null) {
                //拓展经理查询
                String superOrgCode;
                if ("AGENT".equals(managerInfo.getSignInstType())) {
                    //拓展经理签约机构为【代理商】,查询代理商的管理机构作为上级机构查询
                    AgentInfo agentInfo = agentInfoMapper.selectAgentInfoByPrimaryKey(instId, managerInfo.getSignInstId());
                    if (null == agentInfo || !"01".equals(agentInfo.getAgentStatus())) {
                        rglog.error("代理商不存在或代理商状态非正式<{}>", JSONObject.toJSONString(agentInfo));
                        throw new BizException(RespCodeEnum.AGENT_ERROR.getRespCode(), RespCodeEnum.AGENT_ERROR.getRespDesc());
                    }
                    superOrgCode = agentInfo.getManageInstId();
                } else {
                    superOrgCode = managerInfo.getSignInstId();
                }
                OrganizationMapper organizationMapper = new OrganizationMapperImpl();
                List<Organization> organizationList = organizationMapper.selectOrgInfoByInstCodeAndInstName(instId, superOrgCode, null, null);
                if (organizationList == null || organizationList.size() == 0) {
                    rglog.info("根据查询条件查询到0条代理机构信息!");
                    agentMchntListQueryResponse.setTotalPage(BompAppParamConstant.INT_ZERO);
                    agentMchntListQueryResponse.setTotalRows(BompAppParamConstant.INT_ZERO);
                    agentMchntListQueryResponse.setRespCode(RespCodeEnum.QUERY_DATA_IS_NULL.getRespCode());
                    agentMchntListQueryResponse.setRespDesc(RespCodeEnum.QUERY_DATA_IS_NULL.getRespDesc());
                    return bizResponse;
                }
                StringBuffer instCodes = new StringBuffer();
                for (int index = 0; index < organizationList.size(); index++) {
                    instCodes.append(organizationList.get(index).getOrgCode());
                    if (index != organizationList.size() - 1) {
                        instCodes.append(",");
                    }
                }
                manageInstIds = instCodes.toString();
            }

            if (-1 == pageIndex || -1 == pageSize) {
                /* 根据代理机构编号查询或代理机构名称模糊查询或根据签约机构代码查询 */

                List<AgentInfo> agentInfoList = agentInfoMapper.bompSelectAgentInfoByManageInstIds(instId, agentMchntNo, agentMchntName, signInstId, manageInstIds);
                /* 按照创建时间降序排序 */
                // agentInfoList = agentInfoList.stream().sorted(Comparator.comparing(AgentInfo::getCreateTime)).collect(Collectors.toList());
                // Collections.reverse(agentInfoList);
                int totalRows = agentInfoList.size();//过滤前总记录数
                List<AgentMchntInfoBean> agentMchntInfoBeanList = new ArrayList<>();
                agentInfoList.forEach(item -> convAgentInfo(item, agentMchntInfoBeanList));
                /* 查询结果赋值 */
                agentMchntListQueryResponse.setTotalRows(totalRows);//总记录数
                agentMchntListQueryResponse.setAgentMchntInfoList(agentMchntInfoBeanList);
            } else {
                PageInfo pageInfo = new PageInfo();
                pageInfo.setPageIndex(pageIndex);
                pageInfo.setPageSize(pageSize);
                PageResult pageResult = agentInfoMapper.bompSelectAgentInfoByPageAndManageInstIds(instId, agentMchntNo, agentMchntName, signInstId, manageInstIds, pageInfo);

                if (null == pageResult || null == pageResult.getPageInfo() || pageResult.getResult().isEmpty()) {
                    rglog.info("根据查询条件查询到0条代理机构信息!");
                    agentMchntListQueryResponse.setTotalPage(BompAppParamConstant.INT_ZERO);
                    agentMchntListQueryResponse.setTotalRows(BompAppParamConstant.INT_ZERO);
                    agentMchntListQueryResponse.setRespCode(RespCodeEnum.QUERY_DATA_IS_NULL.getRespCode());
                    agentMchntListQueryResponse.setRespDesc(RespCodeEnum.QUERY_DATA_IS_NULL.getRespDesc());
                    return bizResponse;
                }

                /* 根据取出记录条数做对应处理 */
                List<AgentInfo> agentInfoList = new ArrayList<>();
                for (Object object : pageResult.getResult()) {
                    agentInfoList.add((AgentInfo) object);
                }

                rglog.info("SIZE=<{}>", pageResult.getResult().size());
                /* 按照创建时间降序排序 */
                agentInfoList = agentInfoList.stream().sorted(Comparator.comparing(AgentInfo::getCreateTime)).collect(Collectors.toList());
                Collections.reverse(agentInfoList);

                List<AgentMchntInfoBean> agentMchntInfoBeanList = new ArrayList<>();
                agentInfoList.forEach(item -> convAgentInfo(item, agentMchntInfoBeanList));

                agentMchntListQueryResponse.setAgentMchntInfoList(agentMchntInfoBeanList);

                agentMchntListQueryResponse.setTotalPage(pageResult.getPageInfo().getTotalPage());
                agentMchntListQueryResponse.setTotalRows(pageResult.getPageInfo().getTotalRows());
            }
        }

        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        AgentMchntListQueryResponse agentMchntListQueryResponse = (AgentMchntListQueryResponse) bizResponse.getResult();
        ConvertUtil.convertInput(agentMchntListQueryResponse);
    }

    /**
     * 将数据库表结构对象转换成接口对象
     *
     * @param agentInfo        数据库表结构对象
     * @param channelInfoBeans 接口对象
     */
    private void convAgentInfo(AgentInfo agentInfo, List<AgentMchntInfoBean> channelInfoBeans) {
        if ("01".equals(agentInfo.getAgentStatus())) {
            //只展示正式的数据  00-非正式   01-正式   02-停用 03-已注销
            AgentMchntInfoBean agentMchntInfoBean = new AgentMchntInfoBean();
            BeanUtil.beanCopy(agentInfo, agentMchntInfoBean);
            agentMchntInfoBean.setAgentMchntNo(agentInfo.getAgentCode());//代理机构代码
            agentMchntInfoBean.setAgentMchntName(agentInfo.getAgentName());//代理机构名称
            agentMchntInfoBean.setSuperAgentMchntNo(agentInfo.getSuperAgentCode());//上级代理机构代码
            agentMchntInfoBean.setAgentMchntStatus(agentInfo.getAgentStatus());
            agentMchntInfoBean.setSignInstId(agentInfo.getManageInstId());
            AgentInfoMapper agentInfoMapper = new AgentInfoMapperImpl();
            try {
                AgentInfo superAgentInfo = agentInfoMapper.selectAgentInfoByPrimaryKey(agentInfo.getInstId(), agentInfo.getSuperAgentCode());
                if (null != superAgentInfo) {
                    agentMchntInfoBean.setSuperAgentMchntName(superAgentInfo.getAgentName());//上级代理机构名称
                }
            } catch (Exception e) {
                rglog.error("获取该机构的签约机构信息失败,该机构代码:<{}>,签约机构代码:<{}>", agentInfo.getAgentCode(), agentInfo.getManageInstId());
            }

            agentMchntInfoBean.setSignInstId(agentInfo.getManageInstId());//签约机构代码
            OrganizationMapper organizationMapper = new OrganizationMapperImpl();
            try {
                Organization organization = organizationMapper.selectOrganizationByPrimaryKey(agentInfo.getInstId(), agentInfo.getManageInstId());
                if (null != organization) {
                    agentMchntInfoBean.setSignInstName(organization.getOrgName());//签约机构名称
                }
            } catch (Exception e) {
                rglog.error("获取该机构的签约机构信息失败,该机构代码:<{}>,签约机构代码:<{}>", agentInfo.getAgentCode(), agentInfo.getManageInstId());
            }
            channelInfoBeans.add(agentMchntInfoBean);
        }
    }
}
